import { useState, useEffect } from 'react';
import { Card, Button, Space, Table, Badge, Tag, Divider, Modal, Popconfirm } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import IndexStyle from '@/pages/index.less';
import { connect, useHistory } from 'umi';
import { useKey } from '@/hooks';

import { Chart } from '@antv/g2';
import { changeFocus, delArticles,changeStatu } from '@/api/article'

function ArticleList(props: any) {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [pageInfo, setPageInfo] = useState({ page: 1, pageSize: 8 })
  // const location = useLocation()
  const history = useHistory()

  let {
    dispatch,
    articleAll: { list, total },
  } = props;
  // 給数据添加key
  list = useKey(list);

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  // 是否显示隐藏内容
  const hasSelected = selectedRowKeys.length > 0;
  // 获取初始数据
  useEffect(() => {
    dispatch({ type: 'articleAll/INIT', pageInfo });
  }, []);
  //表格改变
  const onChange = (page: number, pageSize: number) => {
    dispatch({ type: 'articleAll/INIT', pageInfo: { page, pageSize } });
  }
  //弹框
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
    setTimeout(() => {
      // 准备数据
      const data = [
        { genre: 'Sports', sold: 275 },
        { genre: 'Strategy', sold: 115 },
        { genre: 'Action', sold: 120 },
        { genre: 'Shooter', sold: 350 },
        { genre: 'Other', sold: 150 },
      ];

      // 初始化图表实例
      const chart = new Chart({
        container: 'c1',
        width: 400, // 图表高度
        height: 400, // 图表宽度
      });

      // 声明可视化
      chart
        .interval() // 创建一个 Interval 标记
        .data(data) // 绑定数据
        .encode('x', 'genre') // 编码 x 通道
        .encode('y', 'sold'); // 编码 y 通道

      // 渲染可视化
      chart.render();
    }, 0)
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  // 表格颜色数据
  const colorList = ["magenta", "red", "volcano", "orange", "#108ee9", "gold", "lime", "green", "cyan", "blue", "geekblue", "purple"]

  const columns: ColumnsType<any> = [
    {
      title: '标题',
      width: 200,
      dataIndex: 'title',
      key: 'title',
      fixed: 'left',
    },
    {
      title: '状态',
      width: 100,
      dataIndex: 'status',
      key: 'status',
      render: (col: string) => {
        return col === 'draft' ? (
          <Space>
            <Badge status="warning" /> 草案
          </Space>
        ) : (
          <Space>
            <Badge status="success" /> 已发布
          </Space>
        );
      },
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 100,
      render: (col: any) => {
        const num = Math.floor(Math.random() * colorList.length);
        return col!==null?<Tag color={colorList[num]}>{col.label}</Tag>:null;
      },
    },
    {
      title: '标签',
      dataIndex: 'tags',
      key: 'tags',
      width: 200,
      render: (col: any) => {
        const num = Math.floor(Math.random() * colorList.length);
        const html = col.length ? (
          col.map((item: any, index: number) => {
            return <Tag key={index} color={colorList[num]}>{item.label}</Tag>;
          })
        ) : null;
        return html;
      },
    },
    {
      title: '阅读量',
      dataIndex: 'views',
      key: 'views',
      width: 100,
      render: (col: number) => {
        return (
          <Badge
            overflowCount={999}
            className="site-badge-count-109"
            count={col}
            style={{ backgroundColor: '#52c41a' }}
          />
        );
      },
    },
    {
      title: '喜欢数',
      dataIndex: 'likes',
      key: 'likes',
      width: 100,
      render: (col: number) => {
        return (
          <Badge
            overflowCount={999}
            className="site-badge-count-109"
            count={col}
            style={{ backgroundColor: '#d62B88' }}
          />
        );
      },
    },
    {
      title: '发布时间',
      dataIndex: 'publishAt',
      key: 'publishAt',
      width: 200,
      render: (col: any) => {
        return new Date(col).toLocaleString()//时间转换
      },

    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 300,
      render: (col: any) => {
        return (
          <div>
            <Space>
              <a onClick={() => {
                pushEdit(col)
              }}>编辑</a> <Divider type="vertical" />
              {
                col.isRecommended ?
                  <a onClick={() => {
                    changeFocusStatus(col.id, false);
                  }}>撤销首焦</a>
                  : <a onClick={() => {
                    changeFocusStatus(col.id, true);
                  }}>首焦推荐</a>
              }
              <Divider type="vertical" />
              <a onClick={showModal}>查看访问</a> <Divider type="vertical" />
              <Popconfirm
                title="你确定要删除吗?"
                onConfirm={() => {
                  delComment(col.id);
                }}
                style={{ width: '400% !important' }}
                okText="确定"
                cancelText="取消"
              >
                <a key="list-loadmore-del" >删除</a>
              </Popconfirm>
            </Space>
          </div>

        )

      },
    },
  ];
  // 更改首焦信息
  const changeFocusStatus = (id: any, isRecommended: boolean) => {
    changeFocus(id, isRecommended).then((res) => {
      dispatch({ type: 'articleAll/INIT', pageInfo });
    });
  }
// 更改状态信息 status publish
const changeStatus = (id: any, status: string) => {
  changeStatu(id, status).then((res) => {
    dispatch({ type: 'articleAll/INIT', pageInfo });
  });
}
  //删除
  const delComment = (id: string) => {
    delArticles(id).then((res) => {
      dispatch({ type: 'articleAll/INIT', pageInfo });
    });
  };
  //跳转到编辑页面
  const pushEdit = (item: any) => {
    history.push('/edit/'+item.id,{state:item})
   }
   //刷新
   const refresh = ()=>{
    history.push('/article/articleAll')
    dispatch({ type: 'articleAll/INIT', pageInfo });
   }
  return (
    <div className={IndexStyle.mt20}>
      <Modal title="访问统计" open={isModalOpen} onCancel={handleCancel} footer={null}>
        <div id='c1'></div>
      </Modal>


      <Card
        title={
          hasSelected ? (
            <div style={{ marginBottom: 16 }}>
              <Space>
                <Button
                onClick={() => {
                  changeStatus({ ...selectedRowKeys }, "publish");
                }}
                >发布</Button>
                <Button
                  onClick={() => {
                    changeStatus({ ...selectedRowKeys }, "draft");
                  }}
                >草稿</Button>
                <Button
                  onClick={() => {
                    changeFocusStatus({ ...selectedRowKeys }, true);
                  }}
                >首焦推荐</Button>
                <Button onClick={() => {
                  changeFocusStatus({ ...selectedRowKeys }, false);
                }}>撤销首焦</Button>
                <Popconfirm
                  title="你确定要删除吗?"
                  onConfirm={() => {
                    delComment(JSON.stringify({ ...selectedRowKeys }));
                  }}
                  style={{ width: '400% !important' }}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button danger>删除</Button>
                </Popconfirm>


              </Space>
            </div>
          ) : (
            ''
          )
        }
        extra={
          <Space>
            <Button icon={<PlusOutlined />} type="primary" onClick={()=>{
              history.push('/add')
            }}>
              新建
            </Button>
            <Button onClick={refresh}>刷新</Button>
          </Space>
        }
      >
        <Table
          pagination={{
            total,
            pageSizeOptions: [8, 12, 24, 36],
            defaultPageSize: 8,
            showSizeChanger: true,
            showTotal: (total: number) => {
              return <>共{total}条</>
            },
            onChange
          }}

          rowSelection={rowSelection}
          columns={columns}
          dataSource={list}
          scroll={{ x: 1500, y: 400 }}
        />
      </Card>

    </div>
  );
}

const mapStateToProps = (state: any) => {
  const { articleAll } = state;
  // mapStateToProps 中return的内容会添加到组件的props上
  return {
    articleAll,
  };
};
export default connect(mapStateToProps)(ArticleList);
